package com.lixl.activemq;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;

import org.apache.activemq.command.ActiveMQTextMessage;

/**
 * <a href="http://activemq.apache.org/activemq-590-release.html">Active
 * MQ下载</a>
 * 
 * @author Administrator
 *
 */
public class QueueDemo {

	public static void main(String[] args) throws JMSException {
		new Producer().start();
		//new Receiver("消费者1", 1000 * 10).start();
		//new Receiver("消费者2", 1000 * 10).start();
	}

}

class Producer extends AbstractActiveMQThread {

	public Producer() throws JMSException {
		Destination destination = session.createQueue("FirstQueue");
		producer = session.createProducer(destination);
	}

	@Override
	public void run() {
		try {
			int i=0;
			while(i<1000){
				ActiveMQTextMessage message = new ActiveMQTextMessage();
				message.setText("abd" + i);
				if(sendMessage(message)){
					i++;
				}
			}
			System.out.println("send message success");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			super.close();
		}
	}

	private boolean sendMessage(Message message) {
		try {
			producer.send(message);
			System.out.println("发送消息："+message.getJMSMessageID()+"\t"+((ActiveMQTextMessage)message).getText());
			return true;
		} catch (JMSException e) {
			e.printStackTrace();
			return false;
		}
	}
}

class Receiver extends AbstractActiveMQThread {

	long timeout = 10000;

	public Receiver(String name, long timeout) throws JMSException {
		super();
		consumer = session.createConsumer(session.createQueue("FirstQueue"));
		this.timeout = timeout;
		this.setName(name);
	}

	private void acceptMessage() {
		while (true) {
			String messageId = "";
			String text = "";
			try {
				TextMessage message = (TextMessage) consumer.receive(timeout);
				if(message!=null){
					messageId = message.getJMSMessageID();
					text = message.getText();
				}
			} catch (JMSException e) {
				e.printStackTrace();
			}finally{
				if (messageId!=null && messageId.length()>0 && text!=null && text.length()>0) {
					System.out.println("收到消息" +messageId+"\t"+ text +"\t"+this.getName());
				} else {
					super.close();
					break;
				}
			}
		}
	}

	@Override
	public void run() {
		acceptMessage();
	}
}
